package vin.echo.core.web;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import vin.echo.core.ServiceContext;
import vin.echo.core.exception.WebStatusException;
import vin.echo.core.request.EchoMehod;
import vin.echo.core.request.Protocol;

/**
 */
public class WebAction extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 5378374825620057218L;
	
	private static final Logger LOG=Logger.getLogger(WebAction.class);
	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public WebAction() {
		super();
	}

	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		LOG.debug("do get    "+request.getRequestURI());
		handleQuery(request, response,EchoMehod.GET);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		LOG.debug("do post    "+request.getRequestURI());
		handleQuery(request, response,EchoMehod.POST);
	}
	
	private void handleQuery(HttpServletRequest request,
			HttpServletResponse response,EchoMehod m) throws IOException {
		Protocol protocol=new Protocol(request,m);
		try {
			String function = protocol.getFunction();
			String query = protocol.getQuery();
			
			if(function==null){
				throw new IllegalAccessException();
			}
			
			ServiceContext.getInstance().service(function, query,request,response);
			
		} catch (WebStatusException e) {
			e.printStackTrace();
			response.setStatus(e.getHttpCode());
		} catch (IllegalAccessException e) {
			//null function
			// redirect to 
			e.printStackTrace();
		}
	}

}
